using IQIGame.Onigao.Framework;

namespace IQIGame.Onigao.Game
{
    public class SendPackage : BasePacket, IConcurrentReusableClass
    {
#if UNITY_EDITOR
        ~SendPackage()
        {
            if (UnityEditor.EditorApplication.isPlaying)
            {
                LogGame.LogError("SendPackage is Be GC!!!");
            }
        }
#endif
        private PackageHeader m_header = new();
        [ClassPoolCheckIgnore]
        private SOutputStream m_outputStream = new();
        private int m_cacheCount = 0;
        /// <summary>
        /// 被缓存的计数
        /// </summary>
        internal int CacheCount
        {
            get
            {
                return m_cacheCount;
            }
            set
            {
                m_cacheCount = value;
                if (m_cacheCount == 0 && !m_active)
                {
                    ConcurrentClassPool<SendPackage>.Put(this);
                }
            }
        }

        public override bool Active
        {
            get
            {
                return m_active;
            }
            set
            {
                m_active = value;
                if (m_cacheCount == 0 && !m_active)
                {
                    ConcurrentClassPool<SendPackage>.Put(this);
                }
            }
        }

        //private static int counter = 0;
        public SendPackage()
        {
            //Debug.LogWarning($"New SendPackage counter = {++counter}");
        }

        public PackageHeader Header
        {
            get
            {
                return m_header;
            }
        }

        public SOutputStream OutputStream
        {
            get
            {
                return m_outputStream;
            }
        }

        public void StartWrite()
        {
            m_outputStream.WriterIndex(m_header.HeaderSize);
        }

        public void FinishWrite()
        {
            m_header.Length = m_outputStream.Size;
            m_outputStream.SetInt(0, m_header.Length);
            m_outputStream.SetInt(4, m_header.Messagid);
            m_outputStream.SetInt(8, m_header.Order);
        }

        public void Dispose()
        {
            m_cacheCount = 0;
            m_active = false;
            m_header = null;
            if (m_outputStream != null)
            {
                m_outputStream.Dispose();
                m_outputStream = null;
            }
        }

        public void OnReset()
        {
            m_cacheCount = 0;
            m_active = false;
            m_header.Clear();
            m_outputStream.Clear();
        }

    }
}



